<script lang="ts" setup>
import { useApplyStore, useAuthStore } from '@/store'
import file from '@/api/file'
import { getEnv } from '@/utils/shared.ts'

const emits = defineEmits(['uploaded'])
const { applyId, imageList } = storeToRefs(useApplyStore())
const { token, sessionid } = storeToRefs(useAuthStore())

const uploadUrl = ref(getEnv().apiBase + '/napFileApi/merchant/common/file/upload')

const fileList = ref<any[]>([])
onMounted(async () => {
  if (imageList.value.fileType20.name !== '') {
    const fileinfo = imageList.value.fileType20
    fileinfo.status = 'uploading'
    fileinfo.message = '载入中'
    fileList.value.push(fileinfo)
    fileinfo.url = await file.downloadImage(fileinfo.name)
    fileinfo.status = 'success'
  }
})
const formHeader = {
  'Content-Type': 'form-data',
  'X-Authorization': token.value,
}
const formData = {
  sessionid: sessionid.value,
  businessId: applyId.value,
  refType: '20',
  refId: '1',
  bindingType: '1',
}

async function beforeUpload (UploadFile: any, options: any) {
  // UploadFile  是 uni.uploadFile ， 你也可以自定义设置其它函数
  UploadFile({
    url: options.url,
    filePath: options.filePath,
    fileType: options.fileType,
    header: {
      'Content-Type': 'multipart/form-data',
      'X-Authorization': token.value,
      ...options.headers
    }, //
    formData: options.formData,
    name: options.name,
    success(response: { errMsg: any; statusCode: number; data: string }) {
      if (options.xhrState == response.statusCode) {
        options.onSuccess?.(response, options);
      } else {
        options.onFailure?.(response, options);
      }
    },
    fail(e: any) {
      options.onFailure?.(e, options);
    }
  });
  // 先查是否已经有图片了
  if (imageList.value.fileType20.url !== '') {
    const file1 = imageList.value.fileType20
    // 调用图片删除接口
    const { data } = await file.delImage(file1.name)
    if (data.status === 'success') {
      options.onStart?.(options);
    }
  } else {
    options.onStart?.(options);
  }
} 

function uploadSuccess({ responseText }) {
  if (responseText.statusCode === 200) {
    const data = JSON.parse(responseText.data)
    console.log(data)
    if (data.status === 'success') {
      emits('uploaded', {
        type: 'acct',
        settleAcct: data.data.cardInfo?data.data.cardInfo.settleAcct:'',
      })
      imageList.value.fileType20.name = fileList.value[0].name
      imageList.value.fileType20.url = fileList.value[0].url
    } else {
      uni.showModal({
        title: '识别提示',
        content: data.message
      })
      // 如果失败将置空所有
      emits('uploaded', {
        type: 'acct',
        settleAcct: '',
      })
    }
  }
}

function validate() {
  return new Promise((resolve) => {
    resolve(fileList.value.length !== 0)
  })
}

defineExpose({ validate })

function previewImage(list) {
  if (list.length === 0) {
    return
  }
  uni.previewImage({
    urls: [list[0].url],
  })
}
</script>

<template>
  <div class="acct-loader">
    <div class="loader">
      <nut-uploader v-model:file-list="fileList" :source-type="['camera']" :url="uploadUrl" :data="formData"
        :headers="formHeader" maximum="1" :before-upload="beforeUpload" with-credentials="true" @success="uploadSuccess"
        @file-item-click="previewImage(fileList)">
        <template #uploadIcon>
          <div>
            <image src="/src/static/bankicon.png" mode="heightFix" class="sfz_img" />
          </div>
        </template>
      </nut-uploader>
      <div class="title">银行卡正面</div>
    </div>
  </div>
</template>


<style lang="sass" scoped>
.acct-loader
  width: 100%
  display: flex
  justify-content: space-between
  .loader
    flex: 1
    align-items: center
    justify-content: center
    display: flex
    flex-direction: column
    .title
      text-align: center
      color: #8e8e8e
      margin-top: 10px
      font-size: 12px

.sfz_img
  height: 200rpx
  border: 3px dashed #76cae4
  border-radius: 15rpx
  padding: 5rpx

:deep(.nut-form-item__body)
  align-items: center!important
  
</style>